layui.define(['layer', 'toastr'], function(exports) {
	var $ = layui.jquery;
	var is_mobile = navigator.userAgent.match(/mobile/i);

	get_push();

	//获取最新推送
	function get_push() {
		var d = new Date().getTime();
		$.ajax({
			type : "POST",
			url : push_server + '&' + d,
			dataType : "json",
			success : function(ret) {
				if (ret.status) {
					$msg = $.parseJSON(ret.data.data);
					push_info($msg);
					get_push();
				}
			}
		});
	};

	//显示推送信息
	function push_info($msg) {
		var position;
		if ($msg.action.length) {
			$title = '<h3>[' + $msg.type + '] [' + $msg.action + ']</h3>';
		} else {
			$title = '<h3>[' + $msg.type + ']</h3>';
		}
		$content = '<p class="push-title">' + $msg.title + '</p>' + $msg.content;

		if (is_mobile) {
			position = "toast-top-full-width";
		} else {
			position = "toast-bottom-right";
		}
		toastr.options = {
			"closeButton" : true,
			"positionClass" : position,
			"timeOut" : ws_push_time * 1000000
		};

		var player = document.createElement('audio');

		player.setAttribute('autoplay', 'autoplay');
		player.setAttribute('preload', 'true');
		document.body.appendChild(player);

		var mp3 = document.createElement('source');
		mp3.src = 'Public/res/default.mp3';
		mp3.type = 'audio/mpeg';
		player.appendChild(mp3);

		toastr.info($content, $title);
	}


	$(document).on('click touchstart', '.hide_mobile_chat', function() {
		$('.layui-m-layer1').hide();
		event.stopPropagation();
		return false;
	});

	$(document).on('click touchstart', '#btn-mobile-chat', function() {
		$('.layui-m-layer1').show();
		event.stopPropagation();
		return false;
	});

	var laychat = {
		appName : '消息',
		initUrl : './init.php', // 初始化好友列表和群组接口，这个接口返回个json，格式见
		sendMessageUrl : './send_message.php', // 发消息接口
		membersUrl : './members.php',
		uploadImageUrl : './upload_img.php',
		uploadFileUrl : './upload_file.php',
		chatLogUrl : './chat_log.php',
		bindUrl : './bind.php',
		updateSignUrl : './update_sign.php',
		msgBoxUrl : './msg_box.php',
		agreeUrl : './agree.php',
		getNoticeUrl : './get_notice.php',
		isMobile : false,
		address : 'ws://' + document.domain + ':8282',
		setMin : false,
		findUrl : false,
		inited : 0,
		socket : null,
		jq : null,
		init_btn : function() {
			html_chat = ['<div id="btn-mobile-chat">', '<i class="fa fa-comments" aria-hidden="true"></i>', '<span class="badge" id="chat_count"></span>', '</div>'].join('');
			$('body').append(html_chat);
		},
		open : function() {
			if (this.inited)
				return;
			if (this.isIE6or7())
				return;
			if (!this.jq)
				this.jq = $;
			this.connectWorkerman();
			this.inited = 1;
		},
		isIE6or7 : function() {
			var b = document.createElement('b');
			b.innerHTML = '<!--[if IE 5]><i></i><![endif]--><!--[if IE 6]><i></i><![endif]--><!--[if IE 7]><i></i><![endif]-->';
			return b.getElementsByTagName('i').length === 1;
		},
		connectWorkerman : function() {
			laychat.socket = new WebSocket(laychat.address);
			laychat.socket.onopen = function() {
				laychat.socket.send(JSON.stringify({
					type : 'init'
				}));
			};

			laychat.socket.onmessage = function(e) {
				var msg = JSON.parse(e.data);
				// 如果layim还没有初始化就收到消息则忽略（init消息除外）
				if (!msg.message_type || (msg.message_type != 'init' && !layui.layim))
					return;

				switch(msg.message_type) {
				// 初始化im

				case 'init':
					// ajax请求，绑定client_id和uid
					laychat.jq.post(laychat.bindUrl, {
						client_id : msg.client_id
					}, function(data) {
						if (data.code == 0) {
							// im获得初始化数据，当前用户，好友列表等数据
							laychat.jq.post(laychat.initUrl, {}, function(initData) {
								if (initData.code != 0) {
									alert('laychat服务端返回失败：' + initData.msg);
								} else {
									laychat.initIM(data, initData.data);
								}
							}, 'json');
						} else {
							alert('laychat服务端返回失败：' + data.msg);
						}
					}, 'json');
					return;
				// 添加一个用户到好友列表
				case 'addList':
					if (laychat.jq('#layim-friend' + msg.data.id).length == 0 && layui.layim.cache() && layui.layim.cache().id != msg.data.id) {
						return layui.layim.addList && layui.layim.addList(msg.data);
					}
					if (msg.data.type == 'friend') {
						layui.layim.setFriendStatus && layui.layim.setFriendStatus(msg.data.id, 'online');
					}
					return;
				// 收到一个消息
				case 'chatMessage':

					if (msg.data.type == 'push') {
						get_push();
						return false;
					}
					if (msg.data.type == 'group') {
						if (msg.data.from_id != layui.layim.cache().mine.id) {
							layui.layim.getMessage(msg.data);
						}
					} else if (layui.layim.cache().mine.id != msg.data.id) {
						layui.layim.getMessage(msg.data);
					}
					laychat.unReadMessageCount(layui.layim);
					return;
				case 'msgbox':
					layui.layim.msgbox && layui.layim.msgbox(msg.count);
					return;
				// 退出
				case 'logout':
				// 隐身
				case 'hide':
					return layui.layim.setFriendStatus && layui.layim.setFriendStatus(msg.id, 'offline');
				// 上线
				case 'online':
					return layui.layim.setFriendStatus && layui.layim.setFriendStatus(msg.id, 'online');
				}
			};
			laychat.socket.onclose = laychat.connectWorkerman;
		},
		sendHeartbeat : function() {
			if (this.socket && this.socket.readyState == 1) {
				this.socket.send(JSON.stringify({
					type : 'ping'
				}));
			}
		},
		unReadMessageCount : function(layim) {
			var cache = layim.cache();
			count = 0;
			for (k in cache.message) {
				count += cache.message[k].length;
			}
			if (count == 0) {
				count = '';
			}
			$('#chat_count').text(count);
		},
		initIM : function(msg_data, init_data) {
			if (enable_chat) {
				this.init_btn();
			}
			var unread_msg_tips = function(msg_data) {
				// 离线消息
				for (var key in msg_data.unread_message) {
					layui.layim.getMessage(JSON.parse(msg_data.unread_message[key]));
				}
				if (msg_data.unread_notice_count) {
					// 设置消息盒子未读计数
					layui.layim.msgbox && layui.layim.msgbox(msg_data.unread_notice_count);
				}
				return;
			};

			// layim已经初始化了，则只提示未读消息
			if (this.inited == 2) {
				return unread_msg_tips(msg_data);
			}
			this.inited = 2;

			// 心跳数据，用来保持长链接，避免socket链接长时间不通讯被路由节点防火墙关闭
			setInterval('laychat.sendHeartbeat()', 12000);
			laychat.isMobile = is_mobile;
			var module = laychat.isMobile ? 'mobile' : 'layim';
			layui.use(module, function(layim) {
				if (laychat.isMobile) {
					var mobile = layui.mobile, layim = mobile.layim, layer = mobile.layer;
					layui.layim = layim;
					layui.layer = layer;
				}
				laychat.unReadMessageCount(layui.layim);
				layui.layim.config({
					//初始化接口
					chatTitleColor : "#2794eb",
					isNewFriend : false,
					init : init_data,

					//查看群员接口
					members : {
						url : laychat.membersUrl
					},

					// 上传图片
					uploadImage : {
						url : laychat.uploadImageUrl
					},

					// 上传文件
					uploadFile : {
						url : laychat.uploadFileUrl
					},
					msgbox : laychat.msgBoxUrl,

					//聊天记录地址
					chatLog : laychat.chatLogUrl,
					find : laychat.findUrl,

					//是否授权
					copyright : true,
					title : laychat.appName,
					min : laychat.setMin,
					moreList : [{
						alias : 'msgbox',
						title : '消息盒子',
						iconUnicode : '&#xe645;', //图标字体的unicode，可不填
						iconClass : '' //图标字体的class类名
					}]
				});

				//监听点击更多列表
				layim.on('moreList', function(obj) {
					switch(obj.alias) {
					case 'msgbox':
						layim.panel({
							title : '消息盒子'//分享
							,
							tpl : '<iframe style="border:0px;scrolling:no;padding: 0px;width:100%;height:100%;" src="{{d.data.test}}">'//模版
							,
							data : {//数据
								test : laychat.msgBoxUrl
							}
						});
						//模拟标记“发现新动态”为已读
						layim.showNew('More', false);
						layim.showNew('find', false);
						break;
					}
				});
				//监听发送消息
				layim.on('sendMessage', function(data) {
					laychat.jq.post(laychat.sendMessageUrl, {
						data : data
					}, function(data) {
						if (data.code != 0) {
							layui.layer.msg(data.msg, {
								time : 7000
							});
						}
					}, 'json');
				});

				//监听在线状态的切换事件
				layim.on('online', function(data) {
					laychat.socket.send(JSON.stringify({
						type : data
					}));
				});

				//更改个性签名
				layim.on('sign', function(value) {
					laychat.jq.post(laychat.updateSignUrl, {
						sign : value
					}, function(data) {
						if (data.code != 0) {
							layui.layer.msg(data.msg, {
								time : 7000
							});
						}
					}, 'json');
				});

				//layim建立就绪
				layim.on('ready', function(res) {
					// 离线消息
					laychat.unReadMessageCount(layui.layim);
					return unread_msg_tips(msg_data);
				});
			});
		}
	};
	if (!is_app) {
		web_socket_url = 'Public/layui/js/web_socket.js';
		load_js(web_socket_url, function() {

			// 置服务端websocket地址
			laychat.address = 'ws://' + document.domain + ':8282';

			//最小化
			laychat.setMin = true;
			laychat.msgBoxUrl = msg_box_url;

			// 置服务端websocket地址
			laychat.bindUrl = chat_bind_url;
			laychat.initUrl = chat_init_url;
			laychat.sendMessageUrl = chat_send_message_url;
			laychat.membersUrl = chat_member_url;
			laychat.chatLogUrl = chat_log_url + '&';
			laychat.uploadImageUrl = chat_upload_img_url;
			laychat.uploadFileUrl = chat_upload_file_url;
			console.log(laychat.chatLogUrl);

			// 打开laychat对话框
			laychat.open();
		});
	}
	window.laychat = laychat;
	exports('laychat', {});
});

